package com.fumasoft.dynamic.config;

import com.alibaba.fastjson.JSONObject;
import com.fumasoft.bill.server.constant.CommonConstant;
import com.fumasoft.dynamic.ttl.CustomerTTL;
import com.fumasoft.dynamic.utils.TokenUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

/**
 * 拦截feign进行拦截，并在请求头添加，需要添加的header参数.
 */
@Slf4j
@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 有的feign接口需要token
        String token = null;
        try {
            token = CustomerTTL.tokenInfo.get().getValue();
        } catch (Exception e) {
            // mq消息接受调用部分feign接口不需要token
            token = TokenUtils.DEFAULT_TOKEN;
            log.warn("FeignClientInterceptor 获取token失败 errorMessage：{}", e.getMessage());
        }
        // 设置token
        requestTemplate.header(CommonConstant.TOKEN, JSONObject.toJSONString(CustomerTTL.tokenInfo.get()));
        requestTemplate.header("accessToken", token);
        String body = "";
        byte[] bytes = requestTemplate.request().body();
        if (bytes != null) {
            body = new String(bytes);
        }
        log.info("请求地址:{},header:{},body:{},", requestTemplate.url(), requestTemplate.headers(), body);
    }
}
